package com.learn.dataandfile

import android.content.Context
import android.content.Intent
import android.os.Environment
import android.os.storage.StorageManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import com.exercise.struct.base.BaseActivity
import com.exercise.struct.viewmodel.BaseViewModel
import com.learn.dataandfile.databinding.ActivityAppSpecificStorageBinding
import java.io.File

class AppSpecificStorageActivity :
    BaseActivity<BaseViewModel, ActivityAppSpecificStorageBinding>() {
    override val bindingInflater: (LayoutInflater) -> ActivityAppSpecificStorageBinding
        get() = ActivityAppSpecificStorageBinding::inflate
    override val modelClass: Class<BaseViewModel>
        get() = BaseViewModel::class.java

    companion object {
        fun start(context: Context) {
            Intent(context, AppSpecificStorageActivity::class.java).also {
                context.startActivity(it)
            }
        }
    }

    override fun initData() {
    }

    override fun initView() {
        binding.titleBar.toolbar.run {
            title = "App-specific storage"
            setNavigationOnClickListener { onBackPressedDispatcher.onBackPressed() }
        }
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.btnAccessPersistentFiles -> {
                accessPersistentFiles()
            }

            R.id.btnCreateCacheFiles -> {
                createCacheFiles()
            }

            R.id.btnExternalStorageAvailable -> {
//                val externalStorageWritable = isExternalStorageWritable()
//                val externalStorageReadable = isExternalStorageReadable()

//                selectExternalStorageVolume()

//                accessExternalStoragePersistentFiles()

//                getAppSpecificAlbumStorageDir(this, "myAlbum")
                m()
            }

            else -> {}
        }
    }

    val NUM_BYTES_NEEDED_FOR_MY_APP = 1024 * 1024 * 10L
    private fun m() {
        //获取系统服务 StorageManager
        val storageManager = applicationContext.getSystemService<StorageManager>()!!
        val appSpecificInternalDirUuid = storageManager.getUuidForPath(filesDir)
        val availableBytes = storageManager.getAllocatableBytes(appSpecificInternalDirUuid)
        if (availableBytes >= NUM_BYTES_NEEDED_FOR_MY_APP) {
            storageManager.allocateBytes(appSpecificInternalDirUuid, NUM_BYTES_NEEDED_FOR_MY_APP)
        } else {
            val storageIntent = Intent().apply {
                action = StorageManager.ACTION_CLEAR_APP_CACHE
            }
            startActivityForResult(storageIntent,10001)
        }

    }

    /**
     * 获取外部存储空间中应用专属目录里的Picture目录
     */
    fun getAppSpecificAlbumStorageDir(context: Context, albumName: String): File {
        val file = File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), albumName)
        if (!file.mkdirs()) {
            Log.e("", "Directory not created")
        }
        return file
    }

    private fun accessExternalStoragePersistentFiles() {
        val appSpecificExternalDir = this.getExternalFilesDir(null)
        binding.tvExternalInfo.text =
            "外部存储空间>应用专属目录路径：\n${appSpecificExternalDir?.path}"
        //创建持久文件
        val file = File(appSpecificExternalDir, "a.txt")
        file.createNewFile()

        //创建缓存文件
        val cacheFile = File(this.externalCacheDir, "aaa.tmp")
        cacheFile.createNewFile()
        cacheFile.delete()
    }

    /**
     * 选择主外部存储卷
     */
    private fun selectExternalStorageVolume() {
        //获取所有的外部存储卷
        val externalStorageVolume = ContextCompat.getExternalFilesDirs(this, null)
        //第一个就是主外部存储卷
        val primaryExternalStorage = externalStorageVolume[0]
    }

    /**
     * 检测外部存储卷是否可写
     */
    private fun isExternalStorageWritable(): Boolean {
        return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
    }

    /**
     * 检测外部存储卷是否可读
     */
    private fun isExternalStorageReadable(): Boolean {
        return Environment.getExternalStorageState() in setOf(
            Environment.MEDIA_MOUNTED,
            Environment.MEDIA_MOUNTED_READ_ONLY
        )
    }

    private fun createCacheFiles() {
        val file = File(this.cacheDir, "aaa470542450.tmp")
        // success
        file.delete()
        //error 删不掉
        this.deleteFile("${this.cacheDir.path}/aaa655850900.tmp")
        //删不掉
        this.deleteFile("aaa655850900.tmp")

    }

    private fun accessPersistentFiles() {

        Log.i("AccessPersistentFiles -> filesDir.path", this.filesDir.path)
        Log.i("AccessPersistentFiles -> filesDir.absolutePath", this.filesDir.absolutePath)
        // success
        val aFile = File(this.filesDir, "a.txt")
        aFile.createNewFile()
        // error，b目录不存在,
        val bFile = File(this.filesDir, "b/a.txt")
        bFile.createNewFile()

        //success
        //Context.MODE_PRIVATE 默认覆盖写入
        val fileContent = "Hello world!"
        this.openFileOutput("c.txt", Context.MODE_PRIVATE).use {
            it.write(fileContent.toByteArray())
            it.write("abcde".toByteArray())
        }
        //Context.MODE_APPEND 追加写入
        this.openFileOutput("c.txt", Context.MODE_APPEND).use {
            it.write(fileContent.toByteArray())
            it.write("abcde".toByteArray())
        }

        //读取文件内容
        this.openFileInput("c.txt").bufferedReader().useLines { lines ->
            val fold = lines.fold("") { some, text ->
                "$some\n$text"
            }
            Log.i("AccessPersistentFiles -> openFileInput", fold)
        }
//        // 读取/res/raw目录下的资源文件
//        resources.openRawResource(1).bufferedReader().use {
//
//        }
        this.fileList().forEach {
            Log.i("AccessPersistentFiles -> fileList", it)
        }
        val file = this.getDir("d", Context.MODE_PRIVATE)
        Log.i("AccessPersistentFiles -> getDir", "${file.exists()}")

    }
}